package com.wx.myatomikos.config;


import com.alibaba.druid.pool.xa.DruidXADataSource;
import com.atomikos.jdbc.AtomikosDataSourceBean;
import org.apache.ibatis.session.SqlSessionFactory;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.mybatis.spring.SqlSessionTemplate;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import javax.sql.DataSource;
import java.sql.SQLException;


/**
 * @ClassName DataSourceTwoConfig
 * @Author wx
 * @Description 数据源-2配置
 * @Date 2018-12-27-21:56
 */
@Configuration
@MapperScan(basePackages = "com.wx.myatomikos.dao2*",sqlSessionTemplateRef = "twoSqlSessionTemplate")
public class DataSourceTwoConfig {


    /**
     * @methodName: twoDataSource
     * @author: wx
     * @description: 注入数据源-2
     * @param
     * @date: 2018/12/27
     * @return: javax.sql.DataSource
     */
    @Bean(name = "twoDataSource")
    public DataSource twoDataSource(@Qualifier(value = "dBConfig2") DBConfig2 dbConfig2) throws SQLException {
        DruidXADataSource dataSource = new DruidXADataSource();
        BeanUtils.copyProperties(dbConfig2,dataSource);
        // 将本地事务注册到创 Atomikos全局事务
        AtomikosDataSourceBean xaDataSource = new AtomikosDataSourceBean();
        xaDataSource.setXaDataSource(dataSource);
        xaDataSource.setUniqueResourceName("twoDataSource");
        xaDataSource.setTestQuery("SELECT 1 FROM DUAL");
        return xaDataSource;
    }

    /**
     * @methodName: twoSqlSessionFactory
     * @author: wx
     * @description: 创建工厂
     * @param dataSource
     * @date: 2018/12/27
     * @return: org.apache.ibatis.session.SqlSessionFactory
     */
    @Bean(name = "twoSqlSessionFactory")
    public SqlSessionFactory twoSqlSessionFactory(@Qualifier("twoDataSource") DataSource dataSource) throws Exception {
        SqlSessionFactoryBean bean = new SqlSessionFactoryBean();
        bean.setTypeAliasesPackage("com.wx.myatomikos.entity2");
        bean.setDataSource(dataSource);
        return bean.getObject();
    }


    /**
     * @methodName: twoSqlSessionTemplate
     * @author: wx
     * @description: 创建模板
     * @param sqlSessionFactory
     * @date: 2018/12/27
     * @return: org.mybatis.spring.SqlSessionTemplate
     */
    @Bean(name = "twoSqlSessionTemplate")
    public SqlSessionTemplate twoSqlSessionTemplate(@Qualifier("twoSqlSessionFactory") SqlSessionFactory sqlSessionFactory){
        return new SqlSessionTemplate(sqlSessionFactory);
    }
}
